<template>
  <view class="profile-page">
    <!-- 自定义导航栏 -->
    <up-navbar title="个人信息" :bgColor="navbarBgColor" height="44" fixed placeholder :autoBack="true">
      <template #left>
        <up-icon name="arrow-left" color="#333" size="20" @click="goBack"></up-icon>
      </template>
    </up-navbar>

    <!-- 个人信息列表 -->
    <view class="profile-list">
      <!-- 头像设置 -->
      <view class="list-item" @click="chooseAvatar">
        <view class="item-left">
          <text class="item-label">头像</text>
        </view>
        <view class="item-right">
          <image class="avatar-preview" :src="profileData.avatarUrl" mode="aspectFill" />
          <up-icon name="arrow-right" color="#ccc" size="16"></up-icon>
        </view>
      </view>

      <!-- 昵称设置 -->
      <view class="list-item">
        <view class="item-left">
          <text class="item-label">昵称</text>
        </view>
        <view class="item-right">
          <input class="item-input" type="nickname" :value="profileData.nickName || '未设置'" placeholder="请输入昵称" @input="onNickNameInput" />
        </view>
      </view>

      <!-- 手机号设置 -->
      <view class="list-item">
        <view class="item-left">
          <text class="item-label">手机号</text>
        </view>
        <view class="item-right">
          <button class="item-btn-value" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
            <text class="item-value" v-if="profileData.phoneNumber">{{
              profileData.phoneNumber
            }}</text>
            <text v-else style="color: #f9211c; margin-left: 2px">未绑定</text>
          </button>
        </view>
      </view>

      <!-- 性别设置 -->
      <view class="list-item" @click="editSex">
        <view class="item-left">
          <text class="item-label">性别</text>
        </view>
        <view class="item-right">
          <up-radio-group v-model="profileData.sex" @change="groupChange" placement="row">
            <up-radio activeColor="red" name="1" label="男"></up-radio>
            <up-radio activeColor="red" name="0" label="女"></up-radio>
          </up-radio-group>
        </view>
      </view>
    </view>

    <!-- 系统设置列表 -->
    <view class="settings-list">
      <!-- 退出登录 -->
      <view class="list-item" @click="handleLogout">
        <view class="item-left">
          <text class="item-label logout-text">退出登录</text>
        </view>
        <view class="item-right">
          <up-icon name="arrow-right" color="#ccc" size="16"></up-icon>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { onShow } from '@dcloudio/uni-app';
import {
  getCurrentUserInfo,
  updateUserInfo,
  getPhoneNumber,
  logout as authLogout,
} from "@/utils/auth.js";

const navbarBgColor = ref("#f8f8f8"); // 将背景色从白色改为浅灰色

// 个人资料数据
const profileData = reactive({});

onMounted(() => {
  // loadProfile();
});

// 添加 onShow 钩子，确保每次页面显示时都刷新个人资料
onShow(() => {
  loadProfile();
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      profileData.avatarUrl = res.tempFilePaths[0];
      saveProfile();
      uni.showToast({
        title: "头像更新成功",
        icon: "success",
      });
    },
    fail: () => {
      uni.showToast({
        title: "选择头像失败",
        icon: "none",
      });
    },
  });
};

// 昵称输入处理
const onNickNameInput = (e) => {
  profileData.nickName = e.detail.value;
  saveProfile();
};

// 保存个人资料到本地存储和服务端
const saveProfile = async () => {
  try {
    const result = await updateUserInfo(profileData);
    if (result.success) {
      uni.showToast({
        title: "资料更新成功",
        icon: "success",
      });
    } else {
      uni.showToast({
        title: result.message || "资料更新失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("保存个人资料失败:", error);
    uni.showToast({
      title: "资料更新失败",
      icon: "none",
    });
  }
};

// 加载个人资料
const loadProfile = async () => {
  try {
    // 从本地存储加载
    const storedData = uni.getStorageSync("userInfo");
    if (storedData) {
      Object.assign(profileData, JSON.parse(storedData));
    }
    const currentUser = await getCurrentUserInfo();
    if (currentUser) {
      Object.assign(profileData, currentUser);
    }
  } catch (error) {
    console.error("加载个人资料失败:", error);
    uni.showToast({
      title: '加载个人资料失败',
      icon: 'none'
    });
    return;
  }
};

// 获取手机号
const onGetPhoneNumber = async (e) => {
  console.log('获取手机号回调:', e);
  if (e.detail.errMsg.includes('fail')) {
    uni.showToast({
      title: '获取手机号失败',
      icon: 'none'
    });
    return;
  }
     // 首先获取微信登录code
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  try {
    // 获取加密数据
    const phoneData = {
      code: loginRes.code,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    };
    uni.showLoading({
      title: '绑定中...'
    });
    // 调用解密手机号功能
    const result = await getPhoneNumber(phoneData);
    uni.hideLoading();
    if (result.success) {
      // 更新手机号
      profileData.phoneNumber = result.data.phoneNumber;
      // 保存到本地
      uni.setStorageSync('userInfo', JSON.stringify(profileData));
      uni.showToast({
        title: '手机号绑定成功',
        icon: 'success'
      });
      
      // 保存到服务器
      await saveProfile();
    } else {
      throw new Error(result.message || '手机号解密失败');
    }
  } catch (error) {
    console.error('获取手机号失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: error.message || '手机号绑定失败',
      icon: 'none'
    });
  }
};

// 格式化手机号显示
// const formatPhoneNumber = (phone) => {
//   if (!phone) return '';
//   // 隐藏中间4位数字
//   return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
// };

// 性别改变
const groupChange = (value) => {
  profileData.sex = value;
  saveProfile();
};

// 退出登录
const handleLogout = async () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用封装好的退出登录方法
          await authLogout();
          
          uni.showToast({
            title: "已退出登录",
            icon: "success",
          });
          
          // 延迟跳转回用户中心并刷新页面
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/user/index",
            });
          }, 1500);
        } catch (error) {
          console.error("退出登录失败:", error);
          uni.showToast({
            title: "退出登录失败",
            icon: "none",
          });
        }
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background-color: #f8f8f8;
}

// 列表样式
.profile-list,
.settings-list {
  background: #fff;
  margin: 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: all 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background: #f8f9fa;
    transform: scale(0.98);
  }

  .item-left {
    display: flex;
    align-items: center;
    gap: 24rpx;

    .item-icon {
      width: 60rpx;
      height: 60rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .item-label {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;

      &.logout-text {
        color: #f56c6c;
      }
    }
  }

  .item-right {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .item-input {
      float: right;
      color: #999999;
      text-align: right;
    }

    .item-value {
      font-size: 30rpx;
      color: #666;
      max-width: 300rpx;
      text-align: right;
      // 显示省略号
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &.cache-size {
        color: #409eff;
      }
    }

    .item-btn-value {
      background: none; // 移除背景
      border: none; // 移除边框
      padding: 0; // 移除内边距
      margin: 0; // 移除外边距
      font-size: 30rpx; // 设置字体大小
      color: #666; // 设置文字颜色
      text-align: right; // 右对齐
      outline: none; // 移除焦点轮廓

      // 移除按钮默认样式
      &::after {
        border: none;
      }
    }

    .avatar-preview {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      border: 2rpx solid #e4e7ed;
    }
  }
}

// 弹窗样式
.edit-modal {
  padding: 40rpx;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;

    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .modal-content {
    margin-bottom: 40rpx;
  }

  .modal-footer {
    display: flex;
    gap: 20rpx;

    .up-button {
      flex: 1;
    }
  }
}

// 性别选择
.sex-options {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;

  .sex-option {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
    padding: 30rpx;
    border-radius: 16rpx;
    border: 2rpx solid #e4e7ed;
    transition: all 0.3s ease;
    cursor: pointer;

    &.active {
      border-color: #409eff;
      background: rgba(64, 158, 255, 0.1);
    }

    text {
      font-size: 28rpx;
      color: #333;
    }
  }
}
</style>